package com.jlcloud.core.oauth2.handler;

import com.jlcloud.core.oauth2.exception.ExceptionCode;
import com.jlcloud.core.oauth2.provider.OAuth2Request;
import com.jlcloud.core.oauth2.provider.OAuth2Validation;
import com.jlcloud.core.oauth2.service.OAuth2User;
import com.jlcloud.core.tool.utils.Func;

/**
 * AbstractAuthorizationHandler
 *
 * @author By: JlCloud <br>
 * @Package: com.jlcloud <br>
 * @CreateTime: 2024-12-03 21:45 <br>
 * @Copyright: 2021 www.jilianjituan.com Inc. All rights reserved. <br>
 * @Caution 注意：本内容仅限于冀联人力集团内部传阅，禁止外泄以及用于其他的商业目的 <br>
 */
public abstract class AbstractAuthorizationHandler implements AuthorizationHandler {


	/**
	 * 认证前校验
	 *
	 * @param request 请求信息
	 * @return boolean
	 */
	@Override
	public OAuth2Validation preValidation(OAuth2Request request) {
		if (request.isClientCredentials() || request.isImplicit() || request.isSocial()) {
			return new OAuth2Validation();
		}
		if (request.isPassword() || request.isCaptchaCode()) {
			if (Func.hasEmpty(request.getUsername())) {
				return buildValidationFailure(ExceptionCode.USER_NOT_FOUND);
			}
		}
		return new OAuth2Validation();
	}

	/**
	 * 认证前失败回调
	 *
	 * @param validation 失败信息
	 */
	@Override
	public abstract void preFailure(OAuth2Request request, OAuth2Validation validation);


	/**
	 * 认证校验
	 *
	 * @param user    用户信息
	 * @param request 请求信息
	 * @return boolean
	 */
	@Override
	public OAuth2Validation authValidation(OAuth2User user, OAuth2Request request) {
		if (request.isClientCredentials() || request.isImplicit() || request.isSocial()) {
			return new OAuth2Validation();
		}
		if (Func.hasEmpty(user, user.getUserId())) {
			return buildValidationFailure(ExceptionCode.USER_NOT_FOUND);
		}
		if (Func.isEmpty(user.getAuthorities())) {
			return buildValidationFailure(ExceptionCode.UNAUTHORIZED_USER);
		}
		return new OAuth2Validation();
	}

	/**
	 * 认证成功回调
	 *
	 * @param user 用户信息
	 */
	@Override
	public abstract void authSuccessful(OAuth2User user, OAuth2Request request);

	/**
	 * 认证失败回调
	 *
	 * @param user       用户信息
	 * @param validation 失败信息
	 */
	@Override
	public abstract void authFailure(OAuth2User user, OAuth2Request request, OAuth2Validation validation);

	/**
	 * 构建认证失败返回
	 *
	 * @param errorCode 错误码
	 * @return 认证结果
	 */
	public OAuth2Validation buildValidationFailure(ExceptionCode errorCode) {
		return new OAuth2Validation().setSuccess(false)
			.setCode(errorCode.getCode())
			.setMessage(errorCode.getMessage());
	}

}
